//
//  CLGLocationManager.m
//  CLGLocationApp
//
//  Created by Liu Guocheng on 2018/4/3.
//  Copyright © 2018年 Sumavision. All rights reserved.
//

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"

#import "CLGLocationManager.h"

static const CGFloat kDistanceFilter = 10000;

@interface CLGLocationManager () <CLLocationManagerDelegate, UIAlertViewDelegate>

@end

@implementation CLGLocationManager

+ (CLGLocationManager *)sharedManager
{
    static CLGLocationManager *manager;
    
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[CLGLocationManager alloc] init];
    });
    
    return manager;
}

- (instancetype)init
{
    if (self = [super init]) {
        self.goToSettingsWhenAuthorizationDeny = YES;
        self.manager = [[CLLocationManager alloc] init];
        self.manager.delegate = self;
    }
    return self;
}

- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    CLLocation *currentLocation = [locations lastObject];
    
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (placemarks.count > 0) {
            self.currentPlacemark = placemarks[0];
        }
        
        if (error) {
            error = [NSError errorWithDomain:@"CLGLocationManager" code:-2 userInfo:@{NSLocalizedDescriptionKey: @"无法获取地址信息，请检查网络"}];
        }
        
        if ([self.delegate respondsToSelector:@selector(didGetLocationPlacemark:error:)]) {
            [self.delegate didGetLocationPlacemark:self.currentPlacemark error:error];
        }
    }];
}

- (void)startMonitoring
{
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    switch (status) {
        case kCLAuthorizationStatusDenied:
        {
            if (self.goToSettingsWhenAuthorizationDeny) {
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"定位权限未打开" message:@"需要设置允许定位以获取相关推荐" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
                
                [alertView show];
            }
            NSError *error = [NSError errorWithDomain:@"CLGLocationManager" code:-1 userInfo:@{NSLocalizedDescriptionKey: @"需要打开定位权限"}];
            if ([self.delegate respondsToSelector:@selector(didGetLocationPlacemark:error:)]) {
                [self.delegate didGetLocationPlacemark:nil error:error];
            }
            return;
        }
            break;
        case kCLAuthorizationStatusNotDetermined:
        {

            [_manager requestWhenInUseAuthorization];
        }
            break;
        default:
            break;
    }
    _manager.desiredAccuracy = kCLLocationAccuracyKilometer;
    _manager.distanceFilter = kDistanceFilter;
    
    [_manager startUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    _manager.desiredAccuracy = kCLLocationAccuracyKilometer;
    _manager.distanceFilter = kDistanceFilter;
    [_manager startUpdatingLocation];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    }
}

- (void)externalNavigateToDestination:(CLLocationCoordinate2D)destination name:(NSString *)name
{
    MKMapItem *currentLocation = [MKMapItem mapItemForCurrentLocation];
    CLLocationCoordinate2D desCorrdinate = CLLocationCoordinate2DMake(destination.latitude, destination.longitude);
    MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:desCorrdinate addressDictionary:nil]];
    toLocation.name = name;
    [MKMapItem openMapsWithItems:@[currentLocation, toLocation]
                   launchOptions:@{MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeDriving,
                                   MKLaunchOptionsMapTypeKey:[NSNumber numberWithInteger:MKMapTypeStandard],
                                   MKLaunchOptionsShowsTrafficKey:[NSNumber numberWithBool:YES]}];
}

@end

#pragma GCC diagnostic pop
